import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import '../models/book.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:flutter/foundation.dart' show kIsWeb;

class SettingsPage extends StatelessWidget {
  const SettingsPage({super.key});

  Future<void> _importBook(BuildContext context, String type) async {
    FileType fileType = FileType.custom;
    List<String> allowedExtensions = type == 'txt' ? ['txt'] : ['epub'];
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: fileType,
      allowedExtensions: allowedExtensions,
      withData: kIsWeb, // Web端需要bytes
    );
    if (result != null) {
      final file = result.files.single;
      final prefs = await SharedPreferences.getInstance();
      final booksJson = prefs.getStringList('books') ?? [];
      Book newBook;
      if (kIsWeb) {
        if (type == 'txt') {
          if (file.bytes == null) {
            if (!context.mounted) return;
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(const SnackBar(content: Text('导入失败：未获取到文件内容')));
            return;
          }
          String base64Content = base64Encode(file.bytes!);
          newBook = Book(
            name: file.name,
            type: type,
            contentBase64: base64Content,
          );
          booksJson.add(json.encode(newBook.toJson()));
          await prefs.setStringList('books', booksJson);
          if (!context.mounted) return;
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('导入成功: ${file.name}')));
        } else {
          // web端epub只做临时展示
          if (file.bytes == null) {
            if (!context.mounted) return;
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(const SnackBar(content: Text('导入失败：未获取到文件内容')));
            return;
          }
          newBook = Book(name: file.name, type: type, isTemp: true);
          // 临时存储到全局变量或内存（此处可扩展）
          // _WebTempEpubHolder.bytes = file.bytes!; // 你可根据主项目实现
          if (!context.mounted) return;
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已临时导入: ${file.name}，请在本次会话内阅读')),
          );
        }
      } else {
        if (file.path == null) {
          if (!context.mounted) return;
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('导入失败：未获取到文件路径')));
          return;
        }
        String? savePath = file.path!;
        newBook = Book(name: file.name, type: type, path: savePath);
        booksJson.add(json.encode(newBook.toJson()));
        await prefs.setStringList('books', booksJson);
        if (!context.mounted) return;
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('导入成功: ${file.name}')));
      }
      if (!context.mounted) return;
      Navigator.of(context).pop();
    } else {
      if (!context.mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('未选择文件或导入已取消')));
    }
  }

  void _showImportSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext ctx) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.description),
                title: const Text('导入小说 (txt)'),
                onTap: () => _importBook(context, 'txt'),
              ),
              ListTile(
                leading: const Icon(Icons.image),
                title: const Text('导入漫画 (epub)'),
                onTap: () => _importBook(context, 'epub'),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('设置')),
      body: ListView(
        children: [
          ListTile(
            leading: const Icon(Icons.import_contacts),
            title: const Text('导入书籍'),
            onTap: () => _showImportSheet(context),
          ),
          const ListTile(
            leading: Icon(Icons.source),
            title: Text('书源'),
          ),
          const ListTile(
            leading: Icon(Icons.brightness_6),
            title: Text('主题切换（占位）'),
          ),
          const ListTile(
            leading: Icon(Icons.text_fields),
            title: Text('字体大小（占位）'),
          ),
        ],
      ),
    );
  }
} 